var videoUpdater = {
	
	timeOut : 100,
	timeCalibrate : 0,
	timer : null,
	ajaxCounter : 0,
	
	init : function() {
		return this;
	},
	
	start : function() {
		this.timer = setInterval(this.fire, this.timeOut);
		this.fire();
		$("#timerStatus").text("Timer started");
	},
	
	stop : function() {
		clearInterval(this.timer);
		this.timer = null;
		$("#timerStatus").text("Timer halted");
	},
	
	updateAjaxStatus : function() {
		$("#ajaxStatus").text("Requests pending: " + this.ajaxCounter);
		$("#timerOut").text("Update every: " + this.timeOut + "ms");		
	},
	
	fire : function() {
		videoUpdater.ajaxCounter++;
		videoUpdater.timeCalibrate++;
		videoUpdater.updateAjaxStatus();
		$.get("index.php?m=admin&t=updatevideo", function(data) {
			if (data.search(/Ready/) == -1) {
				$("#updater").append(data);
				$("#toGo > span").text(parseInt($("#toGo > span").text()) - 1);
			} else {
				videoUpdater.stop();
				$("#timerStatus").text("Ready or error, halted");
			}
			videoUpdater.ajaxCounter--;
			videoUpdater.timeCalibrate--;
			videoUpdater.updateAjaxStatus();
		});
		// calibrate timeOut
		if (videoUpdater.timeCalibrate > 10 && videoUpdater.timer) {
			videoUpdater.timeCalibrate = 0;
			videoUpdater.timeOut = videoUpdater.timeOut + 20;
			videoUpdater.stop();
			videoUpdater.start();
		}
	}
		
}

videoUpdater.init();